VERIFIED_BOOT_DIR = $(BINARIES_DIR)/verified_boot
FIT_KEYS_DIR = $(VERIFIED_BOOT_DIR)/keys_fit
RSA_PRIV_FIT = boot_key.key
RSA_PUB_FIT = boot_key.crt
ITS = s32.its
INSTALL_PATH_FIT_KEYS = $(TARGET_DIR)/etc/keys/verifiedboot

ifeq ($(BR2_TARGET_ARM_TRUSTED_FIRMWARE_DTB_DEBUG),y)
DTB_DEBUG = DEBUG=1
else
DTB_DEBUG =
endif

ATF_DTS_NAME += $(call qstrip,$(BR2_TARGET_ARM_TRUSTED_FIRMWARE_DTS_NAME))

ATF_HSE_VERIFIEDBOOT_MAKE_OPTS += \
                    CROSS_COMPILE="$(TARGET_CROSS)" \
                    PLAT=$(ARM_TRUSTED_FIRMWARE_PLATFORM) \
                    $(DTB_DEBUG)

#################################################################################################
# 1. generating a pair of keys
# 2. creating TFA dtbs
# 3. workaround: using an empty file as kernel and dtb because mkimage does not allow only
#    updating atf dtb with public key
# 4. updating atf dtb with public key. This will be used at boot by bootloader to verify kernel
#    signature
#################################################################################################
define ATF_HSE_VERIFIEDBOOT_GENERATE_FIT_KEYS
    @if [ -d "$(VERIFIED_BOOT_DIR)" ]; then \
        echo "VERIFIED_BOOT_DIR exists. Deleting and recreating the directory..."; \
        rm -rf $(VERIFIED_BOOT_DIR); \
    fi
    mkdir -p $(FIT_KEYS_DIR)
    openssl genrsa -out $(FIT_KEYS_DIR)/$(RSA_PRIV_FIT) 2048
    openssl req -batch -new -x509 \
        -key $(FIT_KEYS_DIR)/$(RSA_PRIV_FIT) \
        -out $(FIT_KEYS_DIR)/${RSA_PUB_FIT}

    $(TARGET_MAKE_ENV) $(MAKE) -C $(@D) $(ATF_HSE_VERIFIEDBOOT_MAKE_OPTS) dtbs

    touch $(VERIFIED_BOOT_DIR)/empty_image
    sed -e "s/<kernel_image>/empty_image/g;s/<dtb_blob>/empty_image/g" \
        $(TOPDIR)/package/arm-trusted-firmware/s32.its > $(VERIFIED_BOOT_DIR)/s32_updated.its

    $(HOST_DIR)/bin/mkimage -f $(VERIFIED_BOOT_DIR)/s32_updated.its \
        -K $(@D)/build/$(ARM_TRUSTED_FIRMWARE_PLATFORM)/fdts/$(BR2_TARGET_ARM_TRUSTED_FIRMWARE_DTB) \
        -k $(FIT_KEYS_DIR) \
        -r $(VERIFIED_BOOT_DIR)/dummy_output
endef
ARM_TRUSTED_FIRMWARE_PRE_INSTALL_IMAGES_HOOKS += ATF_HSE_VERIFIEDBOOT_GENERATE_FIT_KEYS

define ATF_HSE_VERIFIEDBOOT_INSTALL_TARGET_CMDS
    $(INSTALL) -d -m 0755 $(INSTALL_PATH_FIT_KEYS)
    $(INSTALL) -m 0644 $(FIT_KEYS_DIR)/boot_key.crt $(INSTALL_PATH_FIT_KEYS)/
    $(INSTALL) -m 0600 $(FIT_KEYS_DIR)/boot_key.key $(INSTALL_PATH_FIT_KEYS)/
    $(INSTALL) -m 0644 $(TOPDIR)/package/arm-trusted-firmware/s32.its \
        $(INSTALL_PATH_FIT_KEYS)/
endef
ARM_TRUSTED_FIRMWARE_POST_INSTALL_TARGET_HOOKS += ATF_HSE_VERIFIEDBOOT_INSTALL_TARGET_CMDS


$(eval $(generic-package))
